package conf

import (
	"0-hun/go-cron/core/logg"
	"bytes"
	"io/ioutil"

	"github.com/spf13/viper"
	"gopkg.in/yaml.v3"
)

type EtcdConf struct {
	EndPoints []string
	Timeout   int
	ConfKey   string `yaml:"confKey"`
}

type Env uint8

const (
	Local Env = iota
	Test
	Gray
	Pro
)

type Config struct {
	Env Env
	Log logg.Log `yaml:"log"`
	Viper *viper.Viper
	Other map[string]string
	Etcd  EtcdConf `yaml:"etcd"`
}

var (
	GConfig *Config
)

func InitConfig(filename string) (err error) {
	var (
		b []byte
	)
	if b, err = ioutil.ReadFile(filename); err != nil {
		return
	}
	GConfig = &Config{Viper: viper.New()}
	GConfig.Viper.SetConfigType("yaml")
	err = GConfig.Viper.ReadConfig(bytes.NewBuffer(b))
	if err = yaml.Unmarshal(b, GConfig); err != nil {
		return
	}
	for k, v := range GConfig.Other {
		GConfig.Viper.Set(k, readYaml(v))
	}
	return

}
func readYaml(filename string) (m interface{}) {
	data, _ := ioutil.ReadFile(filename)
	m = make(map[interface{}]interface{})
	err := yaml.Unmarshal([]byte(data), &m)
	if err != nil {
		return nil
	}
	return m
}
